package com.lagou.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lagou.mappr.TokenMapper;
import com.lagou.pojo.Token;
import com.lagou.service.UserService;
import org.apache.dubbo.config.annotation.Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.util.List;
import java.util.UUID;

/**
 * @ClassName UserServiceImpl
 * @Description
 * @Author playboy
 * @Date 2021/6/25 8:15 下午
 * @Version 1.0
 **/
@Service
@Transactional
public class UserServiceImpl implements UserService {
	private static Logger log = LoggerFactory.getLogger(UserServiceImpl.class);

	@Autowired
	private TokenMapper tokenMapper;

	/**
	 * 注册用户，判断code是否过期
	 *
	 * @param email
	 * @param password
	 * @param code
	 * @return
	 */
	@Override
	public boolean register(String email, String password, String code) {
		Token token = new Token();
		token.setEmail(email);
		token.setToken(UUID.randomUUID().toString());
		token.setPassword(password);
		tokenMapper.insert(token);
		return true;
	}

	/**
	 * 判断邮箱是否已经注册
	 *
	 * @param email
	 * @return
	 */
	@Override
	public boolean isRegistered(String email) {
		QueryWrapper<Token> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("email", email);
		List<Token> tokens = tokenMapper.selectList(queryWrapper);
		if (ObjectUtils.isEmpty(tokens)) {
			//没有注册
			return false;
		}
		return true;
	}

	/**
	 * 登录
	 *
	 * @param email
	 * @param password
	 * @return
	 */
	@Override
	public String login(String email, String password) {
		QueryWrapper<Token> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("email", email);
		queryWrapper.eq("password", password);
		Token token = tokenMapper.selectOne(queryWrapper);
		if (ObjectUtils.isEmpty(token)) {
			//用户名或者密码不对
			return null;
		}
		token.setToken(UUID.randomUUID().toString());
		tokenMapper.updateById(token);
		return token.getToken();
	}

	/**
	 * 查询信息
	 *
	 * @param token
	 * @return
	 */
	@Override
	public String info(String token) {
		QueryWrapper<Token> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("token", token);
		Token token1 = tokenMapper.selectOne(queryWrapper);
		if (ObjectUtils.isEmpty(token1)) {
			return null;
		}
		return token1.getEmail();
	}
}
